package com.lzk.jetpacktest.service

import android.app.IntentService
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import androidx.databinding.DataBindingUtil
import com.lzk.jetpacktest.R
import com.lzk.jetpacktest.databinding.ActivityServiceBinding

class ServiceActivity : AppCompatActivity() {

    private lateinit var mBinding: ActivityServiceBinding

    private var mMyServiceConnection: ServiceConnection? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = DataBindingUtil.setContentView(this,R.layout.activity_service)

        mMyServiceConnection = object : ServiceConnection{
            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                val binder = service as MyBinder
                Log.d("TAG","onServiceConnected:${binder.getInfo()}")
            }

            override fun onServiceDisconnected(name: ComponentName?) {
                Log.d("TAG","onServiceDisconnected")
            }

        }

        mBinding.btnStart.setOnClickListener {
            startMyService()
        }

        mBinding.btnStop.setOnClickListener {
            stopMyService()
        }

        mBinding.btnBind.setOnClickListener {
            bindMyService()
        }

        mBinding.btnUnbind.setOnClickListener {
            unBindMyService()
        }

    }

    private fun startMyService(){
        val intent = Intent(this,MyService::class.java)
        intent.putExtra("args","我是参数")
        startService(intent)
    }

    private fun stopMyService(){
        val intent = Intent(this,MyService::class.java)
        stopService(intent)
    }

    private fun bindMyService(){
        val intent = Intent(this,MyService::class.java)
        mMyServiceConnection?.let {
            bindService(intent,it,Context.BIND_AUTO_CREATE)
        }
    }

    private fun unBindMyService(){
        mMyServiceConnection?.let {
            unbindService(it)
        }
    }
}